import os

from PyQt5.QtWidgets import QWidget, QGridLayout, QLabel, QLineEdit, QPushButton, QFileDialog, QTableWidget, QCheckBox

from batch_attestat_print import BatchAttestatPrint
from generate_attestat_functions import generate_attestat_marks
from setup_attestat_marks_sizes import SetupAttestatMarksSizes


class AttestatMarks(QWidget):

    def send_data_to_generate_attestat(self):
        name = self.fio_input_field.text()
        attestat_number = self.attestat_number_input_field.text()
        marks = {}
        for row in range(self.table_with_marks.rowCount()):
            if self.table_with_marks.item(row, 0) and self.table_with_marks.item(row, 1):
                marks[self.table_with_marks.item(row, 0).text()] = self.table_with_marks.item(row, 1).text()
        generate_attestat_marks(
            name=name,
            attestat_number=attestat_number,
            marks=marks,
            is_necessary_to_print_back=self.print_background_checkbox.checkState()
        )

    def update_status_bar(self, text):
        self.statusBar.showMessage(text)

    def batch_thread_attachment_print(self):
        filename, ok = QFileDialog.getOpenFileName(self, 'Выберите файл', os.getcwd(), "Excel File (*.xlsx *.ods)")
        if ok:
            self.thread = BatchAttestatMarksPrint(filename, self.print_background_checkbox.checkState())
            self.thread.progress_signal.connect(self.update_status_bar)
            self.thread.start()

    def setup_attestat_marks_sizes(self):
        self.setup_attestat_marks_sizes_window = SetupAttestatMarksSizes()

    def __init__(self, statusBar):
        super(QWidget, self).__init__()
        self.statusBar = statusBar
        self.layout = QGridLayout(self)

        self.layout.addWidget(QLabel('ФИО ученика'), 0, 0)
        self.fio_input_field = QLineEdit()
        self.layout.addWidget(self.fio_input_field, 0, 1)

        self.layout.addWidget(QLabel('Номер аттестата'), 1, 0)
        self.attestat_number_input_field = QLineEdit()
        self.layout.addWidget(self.attestat_number_input_field, 1, 1)

        self.layout.addWidget(QLabel('Оценки'), 2, 0, 1, 2)
        self.table_with_marks = QTableWidget()
        self.table_with_marks.setColumnCount(2)
        self.table_with_marks.setHorizontalHeaderLabels(['Предмет', 'Оценка'])
        self.table_with_marks.setColumnWidth(0, self.table_with_marks.width() // 2)
        self.table_with_marks.horizontalHeader().setStretchLastSection(True)
        self.table_with_marks.setRowCount(30)
        self.layout.addWidget(self.table_with_marks, 3, 0, 1, 2)

        self.print_attestat_button = QPushButton('Напечатать аттестат')
        self.print_attestat_button.released.connect(self.send_data_to_generate_attestat)
        self.layout.addWidget(self.print_attestat_button, 4, 0, 1, 2)

        self.batch_print_attestat_button = QPushButton('Пакетная печать...')
        self.batch_print_attestat_button.released.connect(self.batch_thread_attachment_print)
        self.layout.addWidget(self.batch_print_attestat_button, 5, 0, 1, 2)

        self.settings_attestat_button = QPushButton('Настроить габариты')
        self.settings_attestat_button.released.connect(self.setup_attestat_marks_sizes)
        self.layout.addWidget(self.settings_attestat_button, 6, 0, 1, 2)

        self.print_background_checkbox = QCheckBox('Печатать фон')
        self.print_background_checkbox.setChecked(True)
        self.layout.addWidget(self.print_background_checkbox, 7, 0, 1, 2)


class BatchAttestatMarksPrint(BatchAttestatPrint):
    def __init__(self, filename, is_necessary_to_print_back=True, parent=None):
        super().__init__(filename, is_necessary_to_print_back, parent)
        self.start_message, self.print_error_message, self.progress_message = \
            'Начало печати оценок к аттестатам...', \
                'В строке недостаточно данных, оценки не будут напечатаны', \
                'Печать оценок'
        self.generate_function = generate_attestat_marks
        self.folder_to_store_images = 'marks'
        self.pdf_filename = 'marks.pdf'

    def check_row(self, row):
        if '' in row[:2]:
            return False
        return True

    def run(self):
        super().run()
